package admin

import (
	"ginadmin/app/common"
	"ginadmin/app/dao"
	"ginadmin/app/model"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

type AdminController struct {
	BaseController
}

type AdminUserApi struct {
	model.AdminUser
	StatusStr   string `json:"status_str"`
	LastTimeStr string `json:"last_time_str"`
}

func (con AdminController) Index(c *gin.Context) {

	c.HTML(http.StatusOK, "admin/index.html", nil)
}

type AdminRoleApi struct {
	model.AdminRole
	Ischeck bool
}

func (con AdminController) PostPage(c *gin.Context) {

	strid := c.DefaultQuery("id", "0")

	id, _ := strconv.Atoi(strid)

	if id == 1 {
		con.Error(c, "无法编辑admin用户")
		return
	}

	var admin model.AdminUser

	//查询角色列表
	var rolelist []model.AdminRole
	var rolelistapi []AdminRoleApi

	dao.DB.Find(&rolelist)

	for _, v := range rolelist {
		rolelistapi = append(rolelistapi, AdminRoleApi{
			v, false,
		})
	}

	if id > 0 {
		admin.ID = uint(id)
		dao.DB.First(&admin)

		role := strings.Split(admin.Roles, ",")

		for k, v := range rolelistapi {

			for _, r := range role {

				rid, _ := strconv.Atoi(r)

				if v.ID == uint(rid) {
					rolelistapi[k].Ischeck = true
					break
				}
			}
		}

	}

	c.HTML(http.StatusOK, "admin/edit.html", gin.H{
		"info": admin,
		"role": rolelistapi,
	})
}

type AdminForm struct {
	ID       uint   `form:"id"`
	Username string `form:"username"`
	Password string `form:"password"`
	Roles    string
	Status   bool `form:"status"`
}

func (con AdminController) Post(c *gin.Context) {

	var adminform AdminForm

	roles := c.PostFormMap("roles")

	var rolesstr = ""
	for _, v := range roles {
		rolesstr += v + ","
	}

	rolesstr = strings.TrimRight(rolesstr, ",")

	c.ShouldBind(&adminform)

	if adminform.ID == 1 {
		con.Error(c, "无法编辑admin用户")
		return
	}

	var checkuser model.AdminUser

	dao.DB.Where("id <> ? and username = ?", adminform.ID, adminform.Username).First(&checkuser)
	if checkuser.ID > 0 {
		con.Error(c, "账号重复")
		return
	}

	adminform.Roles = rolesstr

	var admin model.AdminUser

	admin.ID = adminform.ID
	admin.Username = adminform.Username
	admin.Password = adminform.Password
	admin.Roles = adminform.Roles
	admin.Status = adminform.Status

	if adminform.ID == 0 {

		if admin.Password == "" {
			con.Error(c, "请输入密码")
			return
		}

		admin.Password = common.Md5(admin.Password)

		dao.DB.Create(&admin)

	} else {

		dbupd := dao.DB.Select("*")

		omitfield := "last_ip,last_time"

		if admin.Password != "" {
			admin.Password = common.Md5(admin.Password)
		} else {
			omitfield += ",password"
		}

		dbupd.Omit(omitfield).Updates(&admin)
	}

	con.Success(c, "操作成功")
}

func (con AdminController) Delete(c *gin.Context) {

	strid := c.DefaultQuery("id", "0")

	id, _ := strconv.Atoi(strid)

	if id == 1 {
		con.Error(c, "无法删除admin用户")
		return
	}

	var admin model.AdminUser
	admin.ID = uint(id)
	dao.DB.Delete(&admin)

	con.Success(c, "操作成功")
}

func (con AdminController) GetList(c *gin.Context) {

	var list []model.AdminUser

	var apilist []AdminUserApi

	var count int64 = 0

	strpage := c.DefaultQuery("page", "1")
	strlimit := c.DefaultQuery("limit", strconv.FormatInt(int64(common.LIMIT), 10))
	limit, _ := strconv.Atoi(strlimit)
	page, _ := strconv.Atoi(strpage)

	name := c.DefaultQuery("name", "")

	dao.DB.Where("username like ?", name+"%").Limit(limit).Offset((page - 1) * limit).Order("id ASC").Find(&list)
	dao.DB.Where("username like ?", name+"%").Model(&model.AdminUser{}).Count(&count)

	var status_str = ""
	var last_time_str = ""

	for _, v := range list {

		if v.Status {
			status_str = "启用"
		} else {
			status_str = "禁用"
		}

		var last_time = time.Unix(int64(v.LastTime), 0)

		last_time_str = last_time.Format("2006-01-02 15:04:05")

		apilist = append(apilist, AdminUserApi{
			v,
			status_str,
			last_time_str,
		})
	}

	con.Success(c, "ok", &apilist, count)
}
